import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Brain,
  Play,
  Eye,
  RefreshCw,
  CheckCircle,
  AlertCircle,
  Clock,
  Users,
  Calendar,
  MapPin,
  FileText,
  BarChart3,
  Lightbulb,
  Target,
  ArrowRight,
  Pause,
  Square
} from 'lucide-react';
import { cn } from '@/lib/utils';

// React步骤类型枚举
enum ReactStepType {
  THOUGHT = 'thought',
  ACTION = 'action',
  OBSERVATION = 'observation',
  REFLECTION = 'reflection',
  FINAL_ANSWER = 'final_answer'
}

// React步骤接口
interface ReactStep {
  step_id: string;
  step_type: ReactStepType;
  agent_name: string;
  content: string;
  input_data?: Record<string, any>;
  output_data?: Record<string, any>;
  timestamp: string;
  success: boolean;
  error_message?: string;
}

// React工作流接口
interface ReactWorkflow {
  workflow_id: string;
  goal: string;
  steps: ReactStep[];
  current_step: number;
  max_iterations: number;
  context: Record<string, any>;
  status: 'running' | 'completed' | 'error' | 'paused';
  created_at: string;
}

// 步骤类型配置
const stepTypeConfig = {
  [ReactStepType.THOUGHT]: {
    icon: Brain,
    label: '思考',
    color: 'bg-blue-500',
    textColor: 'text-blue-700',
    bgColor: 'bg-blue-50'
  },
  [ReactStepType.ACTION]: {
    icon: Play,
    label: '行动',
    color: 'bg-green-500',
    textColor: 'text-green-700',
    bgColor: 'bg-green-50'
  },
  [ReactStepType.OBSERVATION]: {
    icon: Eye,
    label: '观察',
    color: 'bg-yellow-500',
    textColor: 'text-yellow-700',
    bgColor: 'bg-yellow-50'
  },
  [ReactStepType.REFLECTION]: {
    icon: RefreshCw,
    label: '反思',
    color: 'bg-purple-500',
    textColor: 'text-purple-700',
    bgColor: 'bg-purple-50'
  },
  [ReactStepType.FINAL_ANSWER]: {
    icon: Target,
    label: '最终答案',
    color: 'bg-red-500',
    textColor: 'text-red-700',
    bgColor: 'bg-red-50'
  }
};

// Agent配置
const agentConfig = {
  knowledge_agent: {
    name: '知识Agent',
    icon: Brain,
    color: 'bg-blue-500'
  },
  global_agent: {
    name: '全局Agent',
    icon: Users,
    color: 'bg-green-500'
  },
  data_analysis_agent: {
    name: '数据分析Agent',
    icon: BarChart3,
    color: 'bg-purple-500'
  },
  form_agent: {
    name: '表单Agent',
    icon: FileText,
    color: 'bg-orange-500'
  },
  general_chat_agent: {
    name: '通用对话Agent',
    icon: Users,
    color: 'bg-gray-500'
  },
  system: {
    name: '系统',
    icon: Target,
    color: 'bg-indigo-500'
  }
};

interface ReactWorkflowVisualizationProps {
  className?: string;
}

export const ReactWorkflowVisualization: React.FC<ReactWorkflowVisualizationProps> = ({
  className
}) => {
  const [workflow, setWorkflow] = useState<ReactWorkflow | null>(null);
  const [isRunning, setIsRunning] = useState(false);
  const [currentIteration, setCurrentIteration] = useState(0);
  const [autoScroll, setAutoScroll] = useState(true);
  const stepsContainerRef = useRef<HTMLDivElement>(null);
  const wsRef = useRef<WebSocket | null>(null);

  // 模拟的演示数据
  const demoWorkflow: ReactWorkflow = {
    workflow_id: 'react_demo_001',
    goal: '智能会议助手 - 从需求分析到完整的会议安排',
    steps: [],
    current_step: 0,
    max_iterations: 10,
    context: {
      user_request: '我需要组织一个重要的产品评审会议，参与人员包括技术团队（5人）、产品团队（3人）、设计团队（2人）和市场团队（2人）。会议需要在下周进行，时长大约3小时，需要投影设备和白板。',
      extracted_requirements: {},
      data_collection: {},
      recommendations: {},
      final_plan: {}
    },
    status: 'running',
    created_at: new Date().toISOString()
  };

  // 模拟步骤数据
  const simulateSteps = [
    {
      step_type: ReactStepType.THOUGHT,
      agent_name: 'knowledge_agent',
      content: '分析用户需求：需要为12人的产品评审会议安排合适的会议室，时长3小时，需要投影设备和白板。下一步应该提取具体的需求信息。',
      success: true
    },
    {
      step_type: ReactStepType.ACTION,
      agent_name: 'knowledge_agent',
      content: '执行需求提取：分析用户需求并提取关键信息',
      output_data: {
        participants: { total: 12 },
        duration: '3小时',
        equipment: ['投影设备', '白板'],
        meeting_type: '产品评审会议'
      },
      success: true
    },
    {
      step_type: ReactStepType.OBSERVATION,
      agent_name: 'system',
      content: '成功提取用户需求，识别出会议参与人员、设备需求等关键信息',
      success: true
    },
    {
      step_type: ReactStepType.REFLECTION,
      agent_name: 'system',
      content: '已完成 1/6 个阶段。待完成: data_collection, data_analysis',
      output_data: { completion_percentage: 16.7 },
      success: true
    },
    {
      step_type: ReactStepType.THOUGHT,
      agent_name: 'knowledge_agent',
      content: '需求已提取完成，现在需要查询符合条件的会议室。应该使用GlobalAgent查询容量至少12人且有投影设备和白板的会议室。',
      success: true
    },
    {
      step_type: ReactStepType.ACTION,
      agent_name: 'global_agent',
      content: '执行会议室查询：查询符合要求的会议室',
      output_data: {
        meeting_rooms: [
          { room_id: 'A301', name: '创新会议室A301', capacity: 15 },
          { room_id: 'B205', name: '协作空间B205', capacity: 12 }
        ]
      },
      success: true
    },
    {
      step_type: ReactStepType.OBSERVATION,
      agent_name: 'system',
      content: '成功查询到符合条件的会议室，获得了可用选项',
      success: true
    },
    {
      step_type: ReactStepType.REFLECTION,
      agent_name: 'system',
      content: '已完成 2/6 个阶段。待完成: data_analysis, recommendation_generation',
      output_data: { completion_percentage: 33.3 },
      success: true
    },
    {
      step_type: ReactStepType.THOUGHT,
      agent_name: 'knowledge_agent',
      content: '会议室信息已获取，现在需要分析使用统计数据来找出最佳时间段。应该使用DataAnalysisAgent分析会议室使用模式。',
      success: true
    },
    {
      step_type: ReactStepType.ACTION,
      agent_name: 'data_analysis_agent',
      content: '执行使用统计分析：分析会议室使用趋势和模式',
      output_data: {
        peak_hours: ['10:00-12:00', '14:00-16:00'],
        recommendations: ['建议选择09:00-12:00时段，使用率较低']
      },
      success: true
    },
    {
      step_type: ReactStepType.OBSERVATION,
      agent_name: 'system',
      content: '成功完成数据分析，获得了使用模式和趋势洞察',
      success: true
    },
    {
      step_type: ReactStepType.REFLECTION,
      agent_name: 'system',
      content: '已完成 3/6 个阶段。待完成: recommendation_generation, form_creation',
      output_data: { completion_percentage: 50.0 },
      success: true
    },
    {
      step_type: ReactStepType.THOUGHT,
      agent_name: 'knowledge_agent',
      content: '数据分析完成，现在可以基于收集的信息生成智能推荐方案。需要综合考虑会议室容量、设备配置和使用统计。',
      success: true
    },
    {
      step_type: ReactStepType.ACTION,
      agent_name: 'knowledge_agent',
      content: '执行智能推荐生成：基于数据分析生成最优会议安排方案',
      output_data: {
        primary_recommendation: {
          room: 'A301',
          date: '下周三',
          time: '09:00-12:00',
          confidence: 0.95
        }
      },
      success: true
    },
    {
      step_type: ReactStepType.OBSERVATION,
      agent_name: 'system',
      content: '成功生成智能推荐方案，提供了最优选择和备选方案',
      success: true
    },
    {
      step_type: ReactStepType.REFLECTION,
      agent_name: 'system',
      content: '已完成 4/6 个阶段。待完成: form_creation, user_confirmation',
      output_data: { completion_percentage: 66.7 },
      success: true
    },
    {
      step_type: ReactStepType.THOUGHT,
      agent_name: 'knowledge_agent',
      content: '推荐方案已生成，现在需要创建会议预订表单。使用FormAgent创建包含推荐信息的预订表单。',
      success: true
    },
    {
      step_type: ReactStepType.ACTION,
      agent_name: 'form_agent',
      content: '执行表单创建：创建会议预订申请表单',
      output_data: {
        form_id: 'meeting_booking_001',
        title: '产品评审会议预订申请'
      },
      success: true
    },
    {
      step_type: ReactStepType.OBSERVATION,
      agent_name: 'system',
      content: '成功创建会议预订表单，准备好了提交流程',
      success: true
    },
    {
      step_type: ReactStepType.REFLECTION,
      agent_name: 'system',
      content: '已完成 5/6 个阶段。待完成: user_confirmation',
      output_data: { completion_percentage: 83.3 },
      success: true
    },
    {
      step_type: ReactStepType.THOUGHT,
      agent_name: 'knowledge_agent',
      content: '表单已创建，现在需要生成最终确认摘要，让用户确认整个会议安排方案。',
      success: true
    },
    {
      step_type: ReactStepType.ACTION,
      agent_name: 'general_chat_agent',
      content: '执行用户确认请求：确认最终的会议安排方案',
      output_data: {
        meeting_details: {
          title: '产品评审会议',
          room: '创新会议室A301',
          date_time: '下周三 09:00-12:00'
        }
      },
      success: true
    },
    {
      step_type: ReactStepType.OBSERVATION,
      agent_name: 'system',
      content: '成功生成确认摘要，等待用户最终确认',
      success: true
    },
    {
      step_type: ReactStepType.REFLECTION,
      agent_name: 'system',
      content: '已完成 6/6 个阶段。完成度: 100.0%',
      output_data: { completion_percentage: 100.0 },
      success: true
    },
    {
      step_type: ReactStepType.FINAL_ANSWER,
      agent_name: 'system',
      content: '🎯 智能会议助手 - 完整解决方案\n\n📋 会议需求分析:\n• 会议类型: 产品评审会议\n• 参与人数: 12人\n• 会议时长: 3小时\n\n🏢 推荐方案:\n• 会议室: 创新会议室A301\n• 时间安排: 下周三 09:00-12:00\n• 方案置信度: 95.0%\n\n📝 预订表单: 已创建，等待提交',
      success: true
    }
  ];

  // 启动演示
  const startDemo = async () => {
    setIsRunning(true);
    setWorkflow({ ...demoWorkflow, steps: [] });
    setCurrentIteration(0);

    // 逐步添加步骤
    for (let i = 0; i < simulateSteps.length; i++) {
      await new Promise(resolve => setTimeout(resolve, 2000)); // 2秒间隔
      
      const step: ReactStep = {
        step_id: `step_${i + 1}`,
        ...simulateSteps[i],
        timestamp: new Date().toISOString(),
        input_data: {}
      };

      setWorkflow(prev => {
        if (!prev) return null;
        const newSteps = [...prev.steps, step];
        return {
          ...prev,
          steps: newSteps,
          current_step: newSteps.length
        };
      });

      // 更新迭代计数
      if (step.step_type === ReactStepType.THOUGHT) {
        setCurrentIteration(prev => prev + 1);
      }

      // 自动滚动到最新步骤
      if (autoScroll && stepsContainerRef.current) {
        setTimeout(() => {
          stepsContainerRef.current?.scrollTo({
            top: stepsContainerRef.current.scrollHeight,
            behavior: 'smooth'
          });
        }, 100);
      }
    }

    // 完成工作流
    setWorkflow(prev => prev ? { ...prev, status: 'completed' } : null);
    setIsRunning(false);
  };

  // 停止演示
  const stopDemo = () => {
    setIsRunning(false);
    setWorkflow(prev => prev ? { ...prev, status: 'paused' } : null);
  };

  // 重置演示
  const resetDemo = () => {
    setIsRunning(false);
    setWorkflow(null);
    setCurrentIteration(0);
  };

  // 计算进度
  const getProgress = () => {
    if (!workflow || workflow.steps.length === 0) return 0;
    const reflectionSteps = workflow.steps.filter(s => s.step_type === ReactStepType.REFLECTION);
    if (reflectionSteps.length === 0) return 0;
    const lastReflection = reflectionSteps[reflectionSteps.length - 1];
    return lastReflection.output_data?.completion_percentage || 0;
  };

  // 获取当前阶段
  const getCurrentPhase = () => {
    const progress = getProgress();
    if (progress < 20) return '需求分析';
    if (progress < 40) return '数据收集';
    if (progress < 60) return '数据分析';
    if (progress < 80) return '方案生成';
    if (progress < 100) return '表单创建';
    return '完成确认';
  };

  // 渲染步骤卡片
  const renderStep = (step: ReactStep, index: number) => {
    const config = stepTypeConfig[step.step_type];
    const agentInfo = agentConfig[step.agent_name as keyof typeof agentConfig] || agentConfig.system;
    const Icon = config.icon;
    const AgentIcon = agentInfo.icon;

    return (
      <Card key={step.step_id} className={cn(
        "mb-4 transition-all duration-300 hover:shadow-md",
        config.bgColor,
        step.success ? "border-l-4 border-l-green-500" : "border-l-4 border-l-red-500"
      )}>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className={cn(
                "p-2 rounded-full text-white",
                config.color
              )}>
                <Icon className="h-4 w-4" />
              </div>
              <div>
                <CardTitle className={cn("text-sm font-medium", config.textColor)}>
                  {config.label} #{Math.floor(index / 4) + 1}
                </CardTitle>
                <div className="flex items-center space-x-2 mt-1">
                  <div className={cn(
                    "p-1 rounded text-white",
                    agentInfo.color
                  )}>
                    <AgentIcon className="h-3 w-3" />
                  </div>
                  <span className="text-xs text-gray-600">
                    {agentInfo.name}
                  </span>
                  <span className="text-xs text-gray-400">
                    {new Date(step.timestamp).toLocaleTimeString()}
                  </span>
                </div>
              </div>
            </div>
            <Badge variant={step.success ? "default" : "destructive"}>
              {step.success ? (
                <CheckCircle className="h-3 w-3 mr-1" />
              ) : (
                <AlertCircle className="h-3 w-3 mr-1" />
              )}
              {step.success ? '成功' : '失败'}
            </Badge>
          </div>
        </CardHeader>
        <CardContent className="pt-0">
          <p className="text-sm text-gray-700 leading-relaxed">
            {step.content}
          </p>
          
          {/* 显示输出数据 */}
          {step.output_data && Object.keys(step.output_data).length > 0 && (
            <div className="mt-3 p-3 bg-gray-50 rounded-lg">
              <h4 className="text-xs font-medium text-gray-600 mb-2">输出数据:</h4>
              <pre className="text-xs text-gray-700 whitespace-pre-wrap">
                {JSON.stringify(step.output_data, null, 2)}
              </pre>
            </div>
          )}
          
          {/* 错误信息 */}
          {step.error_message && (
            <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-lg">
              <p className="text-xs text-red-700">
                错误: {step.error_message}
              </p>
            </div>
          )}
        </CardContent>
      </Card>
    );
  };

  return (
    <div className={cn("space-y-6", className)}>
      {/* 控制面板 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center space-x-2">
            <Brain className="h-5 w-5" />
            <span>React多Agent协作可视化</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center space-x-4">
              <Button
                onClick={startDemo}
                disabled={isRunning}
                className="flex items-center space-x-2"
              >
                <Play className="h-4 w-4" />
                <span>开始演示</span>
              </Button>
              
              {isRunning && (
                <Button
                  onClick={stopDemo}
                  variant="outline"
                  className="flex items-center space-x-2"
                >
                  <Pause className="h-4 w-4" />
                  <span>暂停</span>
                </Button>
              )}
              
              <Button
                onClick={resetDemo}
                variant="outline"
                className="flex items-center space-x-2"
              >
                <Square className="h-4 w-4" />
                <span>重置</span>
              </Button>
            </div>
            
            <div className="flex items-center space-x-2">
              <label className="text-sm text-gray-600">
                <input
                  type="checkbox"
                  checked={autoScroll}
                  onChange={(e) => setAutoScroll(e.target.checked)}
                  className="mr-2"
                />
                自动滚动
              </label>
            </div>
          </div>
          
          {/* 工作流状态 */}
          {workflow && (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="flex items-center space-x-2">
                <Target className="h-4 w-4 text-blue-500" />
                <div>
                  <p className="text-xs text-gray-600">目标</p>
                  <p className="text-sm font-medium">{workflow.goal}</p>
                </div>
              </div>
              
              <div className="flex items-center space-x-2">
                <RefreshCw className="h-4 w-4 text-green-500" />
                <div>
                  <p className="text-xs text-gray-600">迭代次数</p>
                  <p className="text-sm font-medium">{currentIteration}/{workflow.max_iterations}</p>
                </div>
              </div>
              
              <div className="flex items-center space-x-2">
                <Clock className="h-4 w-4 text-purple-500" />
                <div>
                  <p className="text-xs text-gray-600">当前阶段</p>
                  <p className="text-sm font-medium">{getCurrentPhase()}</p>
                </div>
              </div>
              
              <div className="flex items-center space-x-2">
                <BarChart3 className="h-4 w-4 text-orange-500" />
                <div>
                  <p className="text-xs text-gray-600">状态</p>
                  <Badge variant={workflow.status === 'completed' ? 'default' : 'secondary'}>
                    {workflow.status === 'running' ? '运行中' : 
                     workflow.status === 'completed' ? '已完成' : 
                     workflow.status === 'paused' ? '已暂停' : '错误'}
                  </Badge>
                </div>
              </div>
            </div>
          )}
          
          {/* 进度条 */}
          {workflow && (
            <div className="mt-4">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-gray-600">整体进度</span>
                <span className="text-sm font-medium">{getProgress().toFixed(1)}%</span>
              </div>
              <Progress value={getProgress()} className="h-2" />
            </div>
          )}
        </CardContent>
      </Card>
      
      {/* 步骤列表 */}
      {workflow && workflow.steps.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <ArrowRight className="h-5 w-5" />
              <span>执行步骤 ({workflow.steps.length})</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div 
              ref={stepsContainerRef}
              className="max-h-96 overflow-y-auto space-y-4"
            >
              {workflow.steps.map((step, index) => renderStep(step, index))}
            </div>
          </CardContent>
        </Card>
      )}
      
      {/* 空状态 */}
      {!workflow && (
        <Card>
          <CardContent className="text-center py-12">
            <Brain className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              React多Agent协作演示
            </h3>
            <p className="text-gray-600 mb-4">
              点击"开始演示"查看智能会议助手的完整工作流程
            </p>
            <Button onClick={startDemo} className="flex items-center space-x-2 mx-auto">
              <Play className="h-4 w-4" />
              <span>开始演示</span>
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default ReactWorkflowVisualization;